package com.rabbiter.oes.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.oes.entity.Message;
import com.rabbiter.oes.entity.Replay;
import com.rabbiter.oes.mapper.MessageMapper;
import com.rabbiter.oes.mapper.ReplayMapper;
import com.rabbiter.oes.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    // 回复数据
    @Autowired
    private ReplayMapper replayMapper;

    @Override
    public IPage<Message> findAll(Page page) {
        IPage<Message> messageIPage = baseMapper.findAll(page);
        List<Message> messages = messageIPage.getRecords();
        for (Message message : messages) {
            Integer id = message.getId();
            List<Replay> replays = replayMapper.findAllByMessageId(id);
            message.setReplays(replays);
        }
        return messageIPage;
    }

    @Override
    public Message findById(Integer id) {
        Message message = baseMapper.selectById(id);
        Optional.ofNullable(message).ifPresent(m -> {
            Integer messageId = m.getId();
            List<Replay> replays = replayMapper.findAllByMessageId(messageId);
            m.setReplays(replays);
        });
        return message;
    }

    @Override
    public int delete(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int update(Message message) {
        return baseMapper.updateById(message);
    }

    @Override
    public int add(Message message) {
        return baseMapper.insert(message);
    }
}
